package com.zxt.web.filter;

import com.zxt.domain.User;
import com.zxt.service.UserService;
import com.zxt.service.impl.UserServiceImpl;
import com.zxt.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       //1.强转
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //2.操作
        //2.1判断是否登录
        User user =(User)request.getSession().getAttribute("user");
        if (user !=null){
            filterChain.doFilter(request,response);
            return;
        }
        //2.2如果没有登录
        Cookie[] cookies = request.getCookies();
        if (cookies != null&&cookies.length>0){
            for (Cookie cookie : cookies){
                if (cookie.getName().equals("userinfo")){
                    String userinfo = cookie.getValue();   //进行加密
                    userinfo= Base64Utils.decode(userinfo);  //进行解密  bbyyy 123
                    String[] arr = userinfo.split("#");
                    if (arr.length==2){
                        String username=arr[0];  //bbyyy
                        String password=arr[1];  //123
                        System.out.println(username+"\t"+password);
                        UserService userService=new UserServiceImpl();
                        try{
                            User u =userService.login(username,password);
                            request.getSession().setAttribute("user",u);
                        }catch (Exception e){
                            System.out.println(e.getMessage());
                            //删除cookie
                            Cookie deleteCookie=new Cookie("userinfo","");
                            deleteCookie.setPath(request.getContextPath());
                            deleteCookie.setMaxAge(0);
                            response.addCookie(deleteCookie);
                        }
                    }
                }
            }
        }
        //放行
        filterChain.doFilter(request,response);
    }
    @Override
    public void destroy() {

    }
}
